//
//  FirstViewController.m
//  shouji138
//
//  Created by administrator on 8/27/09.
//  Copyright 2009 __MyCompanyName__. All rights reserved.
//
#import <CoreFoundation/CoreFoundation.h>
#import "FirstViewController.h"
#import "SrnTeacherAppDelegate.h"
#import "SwitchViewController.h"
#import "AsyncSocket.h"



@implementation FirstViewController





-(IBAction)buttonClick:(id)sender{
	
	if([self doValidation]==NO)
	{
		return nil;
	}
	
	//TODO
	//get port.
	NSString *listenPort = serverport.text;
	
	[SrnTeacherAppDelegate App].port = [listenPort intValue];
	
	//get connection limit.
	NSString *userCount = count.text;
	[SrnTeacherAppDelegate App].userLimit = [userCount intValue];
	
	//startlisten.
	BOOL ret = [[SrnTeacherAppDelegate App] startStop:nil ];
	if(ret == NO){
		[self showAlertView:@"Can not start,Please Change a Port Address!"];
		return nil;
	}
	
	//[[SrnTeacherAppDelegate App].viewController showSecondView];
	[[SrnTeacherAppDelegate App].viewController showTabView];
}

-(BOOL)doValidation
{
	
	if([self isValidPort:serverport.text] == NO)
	{
		
		[self showAlertView:@"Empty or Invalid Port Address!"];
		serverport.text = @"";
		return NO;
	}
	
	return YES;
}

-(void)showAlertView:(NSString *)comment
{
	alertView = [[UIAlertView alloc] initWithTitle: @"Input Error" message:comment 
										  delegate:self cancelButtonTitle:nil 
								 otherButtonTitles:@"OK",nil];
	
    [alertView show];
	[alertView release];
	
}

//Decide whether the Port is valid or not;
-(BOOL)isValidPort:(NSString *)thePort
{
	if([thePort isEqualToString:@""] == YES || ([thePort intValue] <= 0)){
		return NO;
	}
	return YES;
}

/*
 // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        // Custom initialization
    }
    return self;
}
*/

/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
}
*/


#include <ifaddrs.h>
#include <arpa/inet.h>

- (NSString *)getIPAddress
{
	NSString *address = @"error";
	struct ifaddrs *interfaces = NULL;
	struct ifaddrs *temp_addr = NULL;
	int success = 0;
	
	// retrieve the current interfaces - returns 0 on success
	success = getifaddrs(&interfaces);
	if (success == 0)
	{
		// Loop through linked list of interfaces
		temp_addr = interfaces;
		while(temp_addr != NULL)
		{
			if(temp_addr->ifa_addr->sa_family == AF_INET)
			{
				// Check if interface is en0 which is the wifi connection on the iPhone
				if([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"])
				{
					// Get NSString from C String
					address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
				}
			}
			
			temp_addr = temp_addr->ifa_next;
		}
	}
	
	// Free memory
	freeifaddrs(interfaces);
	
	return address;
}

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
	
	//NSString *socketInfo = [NSString stringWithFormat:@"%@, port %hu \n", [listenSocket localHost],[listenSocket localPort]];
	self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"mt-home-background_1.jpg"]];
	NSString *paragraph = [self getIPAddress];
	
	//ip.text = [[shouji138AppDelegate App].listenSocket localHost];
	ip.text = paragraph;
	[SrnTeacherAppDelegate App].ipaddress = paragraph;
	keyboardShown = NO;
	[self registerForKeyboardNotifications];
}


/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
}


- (void)dealloc {
    [super dealloc];
}


// Call this method somewhere in your view controller setup code.
- (void)registerForKeyboardNotifications
{
    [[NSNotificationCenter defaultCenter] addObserver:self
											 selector:@selector(keyboardWasShown:)
												 name:UIKeyboardDidShowNotification object:nil];
	
    [[NSNotificationCenter defaultCenter] addObserver:self
											 selector:@selector(keyboardWasHidden:)
												 name:UIKeyboardDidHideNotification object:nil];
}

// Called when the UIKeyboardDidShowNotification is sent.
/*
 - (void)keyboardWasShown:(NSNotification*)aNotification
 {
 if (keyboardShown)
 return;
 
 NSDictionary* info = [aNotification userInfo];
 
 // Get the size of the keyboard.
 NSValue* aValue = [info objectForKey:UIKeyboardBoundsUserInfoKey];
 CGSize keyboardSize = [aValue CGRectValue].size;
 
 // Resize the scroll view (which is the root view of the window)
 CGRect viewFrame = [scrollView frame];
 viewFrame.size.height -= keyboardSize.height;
 scrollView.frame = viewFrame;
 
 // Scroll the active text field into view.
 CGRect textFieldRect = [name frame];
 [scrollView scrollRectToVisible:textFieldRect animated:YES];
 [scrollView scroll
 keyboardShown = YES;
 }
 */

- (void)keyboardWasShown:(NSNotification*)aNotification
{
	if (keyboardShown)
		return;
	
	self.view.backgroundColor = [UIColor grayColor];
	
	NSDictionary* info = [aNotification userInfo];
	CGSize kbSize = [[info objectForKey:UIKeyboardBoundsUserInfoKey] CGRectValue].size;
	CGRect bkgndRect = ip.superview.frame;
	bkgndRect.size.height += kbSize.height;
	[ip.superview setFrame:bkgndRect];
	[scrollView setContentOffset:CGPointMake(0.0, ip.frame.origin.y -40) animated:YES];
	scrollView.scrollEnabled = NO;
	keyboardShown = YES;
}


// Called when the UIKeyboardDidHideNotification is sent
- (void)keyboardWasHidden:(NSNotification*)aNotification
{
    NSDictionary* info = [aNotification userInfo];
	self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"mt-home-background_1.jpg"]];
    
	// Get the size of the keyboard.
    NSValue* aValue = [info objectForKey:UIKeyboardBoundsUserInfoKey];
    CGSize keyboardSize = [aValue CGRectValue].size;
	
    // Reset the height of the scroll view to its original value
    CGRect viewFrame = [scrollView frame];
    viewFrame.size.height += keyboardSize.height;
    scrollView.frame = viewFrame;
	scrollView.scrollEnabled = YES;
    keyboardShown = NO;
}

- (BOOL) textFieldShouldReturn:(UITextField *)aTextField{
	if(aTextField == serverport){
		[serverport resignFirstResponder];
	}
	return YES;
} 

@end
